import type { RouteRecordRaw } from 'vue-router';

// 菜单状态缓存键
export const MENU_CACHE_KEYS = {
  OPENED_MENUS: 'sidebar_opened_menus',
  ACTIVE_MENU: 'sidebar_active_menu'
} as const;

/**
 * 菜单状态管理工具类
 */
export class MenuStateManager {
  /**
   * 从 localStorage 获取已展开的菜单
   */
  static getOpenedMenus(): string[] {
    try {
      const cached = localStorage.getItem(MENU_CACHE_KEYS.OPENED_MENUS);
      return cached ? JSON.parse(cached) : [];
    } catch {
      return [];
    }
  }

  /**
   * 保存已展开的菜单到 localStorage
   */
  static saveOpenedMenus(openedMenus: string[]): void {
    try {
      localStorage.setItem(MENU_CACHE_KEYS.OPENED_MENUS, JSON.stringify(openedMenus));
    } catch (error) {
      console.warn('Failed to save opened menus:', error);
    }
  }

  /**
   * 从 localStorage 获取当前激活菜单
   */
  static getActiveMenu(): string {
    try {
      return localStorage.getItem(MENU_CACHE_KEYS.ACTIVE_MENU) || '';
    } catch {
      return '';
    }
  }

  /**
   * 保存当前激活菜单到 localStorage
   */
  static saveActiveMenu(activeMenu: string): void {
    try {
      localStorage.setItem(MENU_CACHE_KEYS.ACTIVE_MENU, activeMenu);
    } catch (error) {
      console.warn('Failed to save active menu:', error);
    }
  }

  /**
   * 根据当前路由路径获取应该展开的父级菜单路径
   * 这是核心方法，确保只展开当前路由对应的父级菜单
   */
  static getOpenedMenusByPath(
    menus: RouteRecordRaw[], 
    currentPath: string
  ): string[] {
    // 如果是首页，不展开任何菜单
    if (currentPath === '/' || currentPath === '/overview') {
      return [];
    }

    const openedMenus: string[] = [];
    
    // 递归查找当前路径的父级菜单
    const findParentMenus = (menuList: RouteRecordRaw[], targetPath: string): boolean => {
      for (const menu of menuList) {
        // 检查当前菜单是否匹配目标路径
        if (menu.path === targetPath) {
          return true;
        }
        
        // 如果有子菜单，递归查找
        if (menu.children && menu.children.length > 0) {
          if (findParentMenus(menu.children, targetPath)) {
            // 找到匹配的子菜单，将当前菜单路径添加到展开列表
            openedMenus.unshift(menu.path);
            return true;
          }
        }
      }
      return false;
    };

    findParentMenus(menus, currentPath);
    return openedMenus;
  }

  /**
   * 清除菜单状态缓存
   */
  static clearMenuState(): void {
    try {
      localStorage.removeItem(MENU_CACHE_KEYS.OPENED_MENUS);
      localStorage.removeItem(MENU_CACHE_KEYS.ACTIVE_MENU);
    } catch (error) {
      console.warn('Failed to clear menu state:', error);
    }
  }

  /**
   * 添加展开菜单（用户手动展开时调用）
   */
  static addOpenedMenu(menuPath: string): void {
    const openedMenus = this.getOpenedMenus();
    if (!openedMenus.includes(menuPath)) {
      openedMenus.push(menuPath);
      this.saveOpenedMenus(openedMenus);
    }
  }

  /**
   * 移除展开菜单（用户手动收起时调用）
   */
  static removeOpenedMenu(menuPath: string): void {
    const openedMenus = this.getOpenedMenus();
    const newOpenedMenus = openedMenus.filter(item => item !== menuPath);
    this.saveOpenedMenus(newOpenedMenus);
  }

  /**
   * 根据路由更新菜单展开状态（路由变化时调用）
   */
  static updateOpenedMenusByRoute(
    menus: RouteRecordRaw[], 
    routePath: string
  ): string[] {
    const newOpenedMenus = this.getOpenedMenusByPath(menus, routePath);
    this.saveOpenedMenus(newOpenedMenus);
    return newOpenedMenus;
  }

  /**
   * 调试方法：打印当前菜单状态
   */
  static debugMenuState(menus: RouteRecordRaw[], routePath: string): void {
    console.log('=== Menu State Debug ===');
    console.log('Current Route:', routePath);
    console.log('Should Open Menus:', this.getOpenedMenusByPath(menus, routePath));
    console.log('Cached Opened Menus:', this.getOpenedMenus());
    console.log('Cached Active Menu:', this.getActiveMenu());
    console.log('=======================');
  }
} 